package com.ellison.zookeeperdemo.lock2;

import org.I0Itec.zkclient.ZkClient;

/**
 * ZK 分布式锁 ，属于独占锁
 *
 * @Author Ellison Pei
 * @Date 2021/6/30 21:29
 **/
public abstract class ZkAbstractLock implements Lock{

    private static String connectStr = "119.3.228.104:2181";

    public static String path = "/lock";

    protected ZkClient client = new ZkClient(connectStr);

    /***
     *  尝试获取锁
     *  如果成功，那么正常往下走，走创建订单
     *  如果失败：
     *  1、lock等待，等到前面获取锁的客户释放锁以后；
     *  2、再次去重试获取锁
     * @param
     * @return void
     * @throws Exception
     * @author Ellison.Pei
     * @date 2021/6/30 21:31
     * @version 1.0
     */
    @Override
    public void lock() {
        //尝试获取锁
        if (tryLock()) {
            System.out.println(Thread.currentThread().getName() + "=========获取锁成功！");
        } else {
            waitForLock();
            lock();
        }
    }

    protected abstract boolean tryLock();

    protected abstract void waitForLock();

    @Override
    public void unlock() {
        client.close();
    }
}
